#include "mainwindow.h"
#include <QMessageBox>
#include <QDateTime>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QFileDialog>
#include <QLabel>
#include <QStandardPaths>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QComboBox>
#include <QtWidgets/QApplication>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), backupManager(new BackupManager(this)), syncManager(new SyncManager(this)),
    settings(new Settings("MyCompany", "FileBackupTool")), backupWidget(nullptr), syncWidget(nullptr),
    isProcessing(false), taskManager(new TaskManager(backupManager, syncManager, this)) {
    // 创建 UI 组件
    createUI();

    // 设置窗口的初始大小
    resize(970, 900);  // 设置窗口大小为 800x600 像素

    // 备份管理连接信号和槽
    connect(backupManager, &BackupManager::progressUpdated, this, &MainWindow::updateProgress);
    connect(backupManager, &BackupManager::finished, this, [this] {
        QMessageBox::information(this, "备份完成", "备份任务已完成！");
    });

    // 初始化备份日志文件
    qDebug() << "初始化备份日志文件...";
    initializeBackupLogFile();
    qDebug() << "初始化备份日志文件完成";

    // 连接 BackupManager 的 logMessage 信号到 onLogMessage 槽函数
    connect(backupManager, &BackupManager::logMessage, this, &MainWindow::onBackupLogMessage);

    // 初始化同步日志文件
    qDebug() << "初始化同步日志文件...";
    initializeSyncLogFile();
    qDebug() << "初始化同步日志文件完成";

    // 连接 SyncManager 的 logMessage 信号到 onLogMessage 槽函数
    connect(syncManager, &SyncManager::logMessage, this, &MainWindow::onSyncLogMessage);

    // 同步管理器的信号和槽连接
    connect(syncManager, &SyncManager::progressSyncUpdated, this, &MainWindow::updateSyncProgress);
    connect(syncManager, &SyncManager::finished, this, [this] {
        QMessageBox::information(this, "同步完成", "同步任务已完成！");
    });

    // 初始化定时器
    autoBackupTimer = new QTimer(this);
    connect(autoBackupTimer, &QTimer::timeout, this, &MainWindow::onAutoBackupTimer);

    // 加载设置
    loadSettings();

    // 连接 TaskManager 的信号
    connect(taskManager, &TaskManager::taskStarted, this, [this](const QString &description) {
        taskQueueList->addItem(description);
    });
    connect(taskManager, &TaskManager::taskCompleted, this, [this](const QString &description) {
        // 可以在这里找到对应的项并标记为完成，或者简单地添加一条完成信息
        taskQueueFinishList->addItem(description);
        // // 只移除任务描述信息
        // QString taskPattern = "%1: 备份: %2 -> %3";
        // for (int i = 0; i < taskQueueList->count(); ++i) {
        //     QListWidgetItem *item = taskQueueList->item(i);
        //     if (item->text().startsWith(taskPattern.arg(-1, "", ""))) { // 使用无效参数匹配
        //         if (description.contains(item->text())) {
        //             delete item; // 删除项目并释放内存
        //             break;
        //         }
        //     }
        // }
    });
}

MainWindow::~MainWindow() {
    delete backupManager;
    delete settings;
    delete syncManager;
}

void MainWindow::createUI() {
    QWidget *centralWidget = new QWidget(this);
    // 创建顶层水平布局
    QVBoxLayout *topLevelLayout = new QVBoxLayout(centralWidget);

    // 初始化中间布局，用于包含左右布局
    QHBoxLayout *middleLayout = new QHBoxLayout();

    mainLayout = new QVBoxLayout(centralWidget);
    // 备份界面组件
    backupWidget = new QWidget(centralWidget);
    QVBoxLayout *backupLayout = new QVBoxLayout(backupWidget);

    // 源目录选择
    QHBoxLayout *sourceLayout = new QHBoxLayout();
    sourceDirLineEdit = new QLineEdit(this);
    QLabel *sourceLabel = new QLabel("源目录", this);
    browseSourceButton = new QPushButton("浏览", this);
    connect(browseSourceButton, &QPushButton::clicked, this, &MainWindow::onBrowseSource);
    sourceLayout->addWidget(sourceLabel);
    sourceLayout->addWidget(sourceDirLineEdit);
    sourceLayout->addWidget(browseSourceButton);

    // 目标目录选择
    QHBoxLayout *targetLayout = new QHBoxLayout();
    targetDirLineEdit = new QLineEdit(this);
    QLabel *targetLabel = new QLabel("目标目录", this);
    browseTargetButton = new QPushButton("浏览", this);
    connect(browseTargetButton, &QPushButton::clicked, this, &MainWindow::onBrowseTarget);
    targetLayout->addWidget(targetLabel);
    targetLayout->addWidget(targetDirLineEdit);
    targetLayout->addWidget(browseTargetButton);

    // 备份按钮
    backupButton = new QPushButton("添加备份", this);
    connect(backupButton, &QPushButton::clicked, this, &MainWindow::onBackupButtonClicked);

    // 返回按钮
    QPushButton *backButton = new QPushButton("返回", this);
    connect(backButton, &QPushButton::clicked, this, [this]() {
        backupWidget->hide();
    });
    QPushButton *syncBackButton = new QPushButton("返回", this);
    connect(syncBackButton, &QPushButton::clicked, this, [this]() {
        syncWidget->hide();
    });

    // 增量备份复选框
    incrementalCheckBox = new QCheckBox("增量备份", this);

    // 最大线程数
    maxThreadsSpinBox = new QSpinBox(this);
    maxThreadsSpinBox->setMinimum(1);
    maxThreadsSpinBox->setMaximum(8); // 根据需要调整最大值
    maxThreadsSpinBox->setValue(4);  // 默认值为4
    QLabel *maxThreadsLabel = new QLabel("最大线程数", this);
    QHBoxLayout *maxThreadsLayout = new QHBoxLayout();
    maxThreadsLayout->addWidget(maxThreadsLabel);
    maxThreadsLayout->addWidget(maxThreadsSpinBox);

    // 自动备份复选框和时间编辑
    autoBackupCheckBox = new QCheckBox("开启自动备份", this);
    connect(autoBackupCheckBox, &QCheckBox::toggled, this, &MainWindow::onAutoBackupCheckBoxToggled);
    autoBackupTimeEdit = new QTimeEdit(QTime(0, 0, 5), this);
    autoBackupTimeEdit->setDisplayFormat("hh:mm:ss");

    // 进度条
    progressBar = new QProgressBar(this);
    progressBar->setObjectName("myProgressBar");
    progressBar->setMinimum(0);
    progressBar->setMaximum(100);

    // 添加到备份布局
    backupLayout->addLayout(sourceLayout);
    backupLayout->addLayout(targetLayout);
    backupLayout->addWidget(incrementalCheckBox);
    backupLayout->addWidget(backupButton);
    backupLayout->addLayout(maxThreadsLayout);
    backupLayout->addWidget(autoBackupCheckBox);
    backupLayout->addWidget(autoBackupTimeEdit);
    backupLayout->addWidget(progressBar);
    backupLayout->addWidget(backButton);  // 添加返回按钮

    backupWidget->setLayout(backupLayout);

    // 同步界面组件
    syncWidget = new QWidget(centralWidget);
    QVBoxLayout *syncLayout = new QVBoxLayout(syncWidget);

    // 源目录选择
    QHBoxLayout *syncSourceLayout = new QHBoxLayout();
    QLabel *syncSourceLabel = new QLabel("同步目录", this);
    syncSourceDirLineEdit = new QLineEdit(this);  // 新增同步源目录编辑框
    QPushButton *syncBrowseSourceButton = new QPushButton("浏览", this);
    connect(syncBrowseSourceButton, &QPushButton::clicked, this, &MainWindow::synconBrowseSource);
    syncSourceLayout->addWidget(syncSourceLabel);
    syncSourceLayout->addWidget(syncSourceDirLineEdit);
    syncSourceLayout->addWidget(syncBrowseSourceButton);

    // 目标目录选择
    QHBoxLayout *syncTargetLayout = new QHBoxLayout();
    syncTargetDirLineEdit = new QLineEdit(this);  // 新增同步目标目录编辑框
    QLabel *syncTargetLabel = new QLabel("待同步目录", this);
    QPushButton *syncBrowseTargetButton = new QPushButton("浏览", this);
    connect(syncBrowseTargetButton, &QPushButton::clicked, this, &MainWindow::synconBrowseTarget);
    syncTargetLayout->addWidget(syncTargetLabel);
    syncTargetLayout->addWidget(syncTargetDirLineEdit);
    syncTargetLayout->addWidget(syncBrowseTargetButton);

    // 双向同步复选框
    resolveConflictsCheckBox = new QCheckBox("反向同步", this);

    // 同步按钮
    syncStartButton = new QPushButton("添加同步", this);
    connect(syncStartButton, &QPushButton::clicked, this, &MainWindow::onSyncButtonClicked);

    // 进度条
    syncProgressBar = new QProgressBar(this);  // 新增同步进度条
    syncProgressBar->setObjectName("mySyncProgressBar");
    syncProgressBar->setMinimum(0);
    syncProgressBar->setMaximum(100);

    // 添加到同步布局
    syncLayout->addLayout(syncSourceLayout);
    syncLayout->addLayout(syncTargetLayout);
    syncLayout->addWidget(resolveConflictsCheckBox);
    syncLayout->addWidget(syncStartButton);
    syncLayout->addWidget(syncProgressBar);
    syncLayout->addWidget(syncBackButton);

    syncWidget->setLayout(syncLayout);

    // 初始界面布局
    mainLayout->addWidget(backupWidget);
    mainLayout->addWidget(syncWidget);

    setCentralWidget(centralWidget);
    // 隐藏备份界面
    backupWidget->show();
    syncWidget->hide();

    // 右侧布局
    rightLayout = new QVBoxLayout(centralWidget);
    {
        // 主界面按钮布局
        QWidget *mainButtonWidget = new QWidget(centralWidget);
        QHBoxLayout *mainButtonLayout = new QHBoxLayout(mainButtonWidget);
        createTaskButton = new QPushButton("创建任务", this);
        connect(createTaskButton, &QPushButton::clicked, this, &MainWindow::onCreateTaskButtonClicked);
        mainButtonLayout->addWidget(createTaskButton);
        mainButtonWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); // 固定高度
        rightLayout->addWidget(mainButtonWidget);

        // 任务类型下拉框
        taskTypeComboBox = new QComboBox(this);
        taskTypeComboBox->addItem("备份文件");
        taskTypeComboBox->addItem("同步文件");
        taskTypeComboBox->hide();
        taskTypeComboBox->hidePopup();
        rightLayout->addWidget(taskTypeComboBox);

        // 任务队列列表控件
        QLabel *taskQueueLabel = new QLabel("任务队列", this);
        taskQueueList = new QListWidget(centralWidget);  // 创建任务队列列表控件
        rightLayout->addWidget(taskQueueLabel);
        rightLayout->addWidget(taskQueueList);

        // 任务队列列表完成详情控件
        QLabel *taskQueueFinishLabel = new QLabel("完成详情", this);
        taskQueueFinishList = new QListWidget(centralWidget);  // 创建任务队列列表控件
        rightLayout->addWidget(taskQueueFinishLabel);
        rightLayout->addWidget(taskQueueFinishList);

        //执行光标选中的任务
        QPushButton *startOneButton = new QPushButton("单个执行", this);
        connect(startOneButton, &QPushButton::clicked, this, &MainWindow::onStartTaskButtonClicked);
        rightLayout->addWidget(startOneButton);

        //一键执行任务队列中所有任务
        QPushButton *allStartButton = new QPushButton("全部执行", this);
        connect(allStartButton, &QPushButton::clicked, this, &MainWindow::startAllTaskButtonClicked);
        rightLayout->addWidget(allStartButton);

        setStyleSheet(
            "QListWidget {"
            "   min-width: 350px;"  // 设置最大宽度
            "}"
            "QPushButton {"
            "   font-size: 20px;"  // 放大字体大小
            "   padding: 15px;"    // 增加内边距
            "   min-width: 100px;" // 最小宽度
            "   min-height: 22px;" // 最小高度
            "}"
            "QLineEdit {"
            "   font-size: 20px;"  // 放大字体大小
            "   padding: 10px;"    // 增加内边距
            "   min-height: 25px;" // 最小高度
            "}"
            "QLabel {"
            "   font-size: 23px;"  // 放大字体大小
            "}"
            "QComboBox {"
            "   font-size: 15px;"  // 放大字体大小
            "   padding: 15px;"    // 增加内边距
            "   min-width: 100px;" // 最小宽度
            "   min-height: 20px;" // 最小高度
            "}"
            "#myProgressBar, #mySyncProgressBar {"
            "   font-size: 20px;"  // 进度条字体大小
            "   min-height: 30px;" // 进度条最小高度
            "   border: 2px solid #0078D7;" // 自定义边框
            "   border-radius: 10px;" // 圆角
            "   background-color: #E0E0E0;" // 背景颜色
            "   text-align: center;" // 文本居中
            "}"
            "QSpinBox, QTimeEdit, QCheckBox{"
            "   font-size: 22px;"  // 放大字体大小
            "}"
            "#progressBarLabel, #syncProgressBarLabel {"
            "   font-size: 20px;"  // 标签字体大小
            "   margin-bottom: 2px;" // 标签下方的间距
            "}"
            "QListWidget {"
            "    font-size: 16px;"
            "}"
            );
    }


    topLevelLayout->setSpacing(0);
    mainLayout->setSpacing(0);
    rightLayout->setSpacing(0);

    // 将左右布局添加到顶层布局中
    middleLayout->addLayout(mainLayout);
    middleLayout->addLayout(rightLayout);

    // 创建一个日志面板
    QWidget *logPanel = new QWidget();
    QVBoxLayout *logLayout = new QVBoxLayout(logPanel);

    // 添加一些控件到日志面板中
    logDisplay = new QTextEdit(); // 用于显示日志信息的文本编辑器
    logDisplay->setReadOnly(true); // 设置为只读模式
    logLayout->addWidget(logDisplay);

    topLevelLayout->addLayout(middleLayout);
    // 将日志面板添加到顶层布局的底部
    topLevelLayout->addWidget(logPanel);

    // 初始化日志文件路径
    logFilePath_ = "/home/kirvecy/qt-Project/copy_sync/backup_log.log";

    // 立即加载日志文件
    loadLogsIntoWidget(logFilePath_);

}

void MainWindow::onCreateTaskButtonClicked() {
    qDebug() << "创建任务按钮被点击";
    connect(taskTypeComboBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &MainWindow::onTaskTypeSelected);
    qDebug() << "下拉框已插入并连接信号";

    taskTypeComboBox->show();  // 显示下拉框
}

void MainWindow::onTaskTypeSelected(int index) {
    qDebug() << "选择了任务类型" << index;

    switch (index) {
    case 0:   // 备份文件
        // 显示备份界面并隐藏同步界面

        backupWidget->show();
        syncWidget->hide();
        break;

    case 1:  // 同步文件
        // 显示同步界面并隐藏备份界面
        syncWidget->show();
        backupWidget->hide();
        break;

    default:
        // 如果没有选择，则隐藏所有界面
        backupWidget->hide();
        syncWidget->hide();
        break;
    }

    // 当选择了一个任务类型时，从布局中移除下拉框
    if (taskTypeComboBox->parentWidget()) {
        mainLayout->removeWidget(taskTypeComboBox);
        taskTypeComboBox->hide();
    }
}

void MainWindow::onStartTaskButtonClicked(){
    int currentRow = taskQueueList->currentRow();
    if (currentRow != -1) {
        qDebug() << "执行当前行任务" << currentRow;

        // 获取当前行的任务ID
        int taskId = currentRow;

        // 执行当前选中的任务
        taskManager->executeTask(taskId);
        QListWidgetItem *item = taskQueueList->item(taskId);
        delete item; // 删除项目并释放内存
        loadLogsIntoWidget(logFilePath_);
    } else {
        qWarning("No task selected");
    }

}

void MainWindow::startAllTaskButtonClicked(){
    qDebug() << "startAllTaskButtonClicked called";
    taskManager->startTasks();
    qDebug()<<"count:"<<taskQueueList->count();

    // 存储所有列表项的指针
    QList<QListWidgetItem*> itemsToDelete;
    for (int i = 0; i < taskQueueList->count(); ++i) {
        QListWidgetItem *item = taskQueueList->item(i);
        itemsToDelete.append(item);
    }

    // 删除所有列表项
    for (QListWidgetItem *item : itemsToDelete) {
        delete item;
    }
    loadLogsIntoWidget(logFilePath_);

}

//备份源目录浏览
void MainWindow::onBrowseSource() {
    QString dir = QFileDialog::getExistingDirectory(this, tr("选择源目录"), QDir::homePath());
    if (!dir.isEmpty()) {
        sourceDirLineEdit->setText(dir);
    }
}

//备份目标目录浏览
void MainWindow::onBrowseTarget() {
    QString dir = QFileDialog::getExistingDirectory(this, tr("选择目标目录"), QDir::homePath());
    if (!dir.isEmpty()) {
        targetDirLineEdit->setText(dir);
    }
}

void MainWindow::synconBrowseSource() {
    QString dir = QFileDialog::getExistingDirectory(this, tr("选择源目录"), QDir::homePath());
    if (!dir.isEmpty()) {
        syncSourceDirLineEdit->setText(dir);
    }
}

void MainWindow::synconBrowseTarget() {
    QString dir = QFileDialog::getExistingDirectory(this, tr("选择目标目录"), QDir::homePath());
    if (!dir.isEmpty()) {
        syncTargetDirLineEdit->setText(dir);
    }
}

void MainWindow::onBackupButtonClicked() {
    qDebug() << "onBackupButtonClicked called";

    QString sourceDir = sourceDirLineEdit->text();
    QString targetDir = targetDirLineEdit->text();
    bool incremental = incrementalCheckBox->isChecked();
    int maxThreads = maxThreadsSpinBox->value(); // 获取最大线程数

    if (sourceDir.isEmpty() || targetDir.isEmpty()) {
        QMessageBox::warning(this, "错误", "请选择源目录和目标目录。");
        return;
    }

    backupManager->setMaxThreads(maxThreads);
    taskManager->addBackupTask(sourceDir, targetDir, incremental);
    taskQueueList->addItem(QString("%1: 备份: %2 -> %3")
                               .arg(taskManager->getBackupCounter() - 1) // 使用上一个任务的ID
                               .arg(sourceDir)
                               .arg(targetDir));
}

void MainWindow::onSyncButtonClicked() {
    qDebug() << "开始同步文件";
    QString sourceDir = syncSourceDirLineEdit->text();
    QString targetDir = syncTargetDirLineEdit->text();
    bool resolveConflicts = resolveConflictsCheckBox->isChecked();

    if (sourceDir.isEmpty() || targetDir.isEmpty()) {
        QMessageBox::warning(this, "错误", "请选择要同步的目录。");
        return;
    }

    // 开始同步
    taskManager->addSyncTask(sourceDir, targetDir, resolveConflicts);
    taskQueueList->addItem(QString("%1: 同步: %2 -> %3")
                               .arg(taskManager->getSyncCounter() - 1) // 使用上一个任务的ID
                               .arg(sourceDir)
                               .arg(targetDir));
}

void MainWindow::onAutoBackupCheckBoxToggled(bool checked) {
    if (checked) {
        startAutoBackupTimer();
    } else {
        stopAutoBackupTimer();
    }
}

void MainWindow::onAutoBackupTimer() {
    if (autoBackupCheckBox->isChecked()) {
        onBackupButtonClicked();
    }
}

void MainWindow::updateProgress(int progress) {
    progressBar->setValue(progress);
    progressBar->setValue(progress);  // 更新同步进度条
}

void MainWindow::updateSyncProgress(int progress) {
    syncProgressBar->setValue(progress);
    syncProgressBar->setValue(progress);  // 更新同步进度条
}

// 初始化备份日志文件
void MainWindow::initializeBackupLogFile() {
    // 获取用户的文档目录
    QString logDir = "/home/kirvecy/qt-Project/copy_sync";
    QDir dir(logDir);
    if (!dir.exists()) {
        if (!dir.mkpath(".")) {
            qDebug() << "无法创建目录: " << logDir;
            return;
        }
    }

    // 创建日志文件名
    QString logFileName = "backup_log.log";
    QString logFilePath = logDir + "/" + logFileName;

    // 检查日志文件是否已经存在
    QFileInfo fileInfo(logFilePath);
    bool fileExists = fileInfo.exists();


    // 打开日志文件
    backupLogFile.setFileName(logFilePath);

    if (backupLogFile.open(QIODevice::Append | QIODevice::Text)) {
        backuplogStream.setDevice(&backupLogFile);
        // 如果文件是新创建的，则写入创建消息
        if (!fileExists) {
            logMessage("备份日志文件已创建: " + logFilePath, Backup);
        }

    } else {
        qDebug() << "无法打开日志文件: " << backupLogFile.errorString();
    }
}

// 初始化同步日志文件
void MainWindow::initializeSyncLogFile() {
    // 获取用户的文档目录
    QString logDir = "/home/kirvecy/qt-Project/copy_sync";
    QDir dir(logDir);
    if (!dir.exists()) {
        if (!dir.mkpath(".")) {
            qDebug() << "无法创建目录: " << logDir;
            return;
        }
    }

    // 创建日志文件名
    QString logFileName = "sync_log.log";
    QString logFilePath = logDir + "/" + logFileName;

    // 检查日志文件是否已经存在
    QFileInfo fileInfo(logFilePath);
    bool fileExists = fileInfo.exists();

    // 打开日志文件
    syncLogFile.setFileName(logFilePath);

    if (syncLogFile.open(QIODevice::Append | QIODevice::Text)) {
        synclogStream.setDevice(&syncLogFile);
        // 如果文件是新创建的，则写入创建消息
        if (!fileExists) {
            logMessage("同步日志文件已创建: " + logFilePath, Sync);
        }
    } else {
        qDebug() << "无法打开日志文件: " << syncLogFile.errorString();
    }
}

// 记录日志消息
void MainWindow::logMessage(const QString &message, LogType type) {
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ");
    if(type == Backup && backuplogStream.device()){
        // 关闭当前的备份日志文件
        backupLogFile.close();
        // 重新打开日志文件
        backupLogFile.open(QIODevice::Append | QIODevice::Text);
        backuplogStream.setDevice(&backupLogFile);

        backuplogStream << timestamp << message << "\n";
        backuplogStream.flush();
    }else if(type == Sync && synclogStream.device()){
        // 关闭当前的同步日志文件
        syncLogFile.close();
        // 重新打开日志文件
        syncLogFile.open(QIODevice::Append | QIODevice::Text);
        synclogStream.setDevice(&syncLogFile);

        synclogStream << timestamp << message << "\n";
        synclogStream.flush();
    }
}

void MainWindow::loadLogsIntoWidget(const QString &filePath)
{
    QFile logFile(filePath);
    if (!logFile.exists()) {
        qWarning() << "日志文件不存在：" << filePath;
        return;
    }

    if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开日志文件：" << filePath;
        return;
    }

    QTextStream in(&logFile);
    QString logContent = in.readAll();

    logFile.close();

    // 将日志内容插入到文本编辑器中
    logDisplay->setPlainText(logContent);
}


// 处理日志消息
void MainWindow::onBackupLogMessage(const QString &message) {
    logMessage(message, Backup);
}

void MainWindow::onSyncLogMessage(const QString &message) {
    logMessage(message, Sync);
}

// 重写 closeEvent 方法
void MainWindow::closeEvent(QCloseEvent *event) {
    if (backupLogFile.isOpen()) {
        backupLogFile.close();
        logMessage("日志文件已关闭", Backup);
    }
    if (syncLogFile.isOpen()) {
        syncLogFile.close();
        logMessage("同步日志文件已关闭", Sync);
    }
    event->accept();
}

void MainWindow::loadSettings() {
    // 从设置中加载配置
    settings->load();
    sourceDirLineEdit->setText(settings->getSourceDir());
    targetDirLineEdit->setText(settings->getTargetDir());
    autoBackupCheckBox->setChecked(settings->isAutoBackupEnabled());
    autoBackupTimeEdit->setTime(settings->getAutoBackupTime());

    if (settings->isAutoBackupEnabled()) {
        startAutoBackupTimer();
    }
}

void MainWindow::saveSettings() {
    // 保存当前配置到设置
    settings->setSourceDir(sourceDirLineEdit->text());
    settings->setTargetDir(targetDirLineEdit->text());
    settings->setAutoBackupEnabled(autoBackupCheckBox->isChecked());
    settings->setAutoBackupTime(autoBackupTimeEdit->time());
    settings->save();
}

void MainWindow::startAutoBackupTimer() {
    QTime time = autoBackupTimeEdit->time();

    int interval = 24 * 60 * 60 * 1000; // 默认每天一次
    if (time.isValid()) {
        QTime midnight(0, 0, 0);
        interval = midnight.secsTo(time) * 1000;
    }
    autoBackupTimer->start(interval);
}

void MainWindow::stopAutoBackupTimer() {
    autoBackupTimer->stop();
}
